package api

import (
	"gin-quickstart/internal/database"
	"gin-quickstart/internal/modules/product/handlers"
	"gin-quickstart/internal/modules/product/services"
	"net/http"

	"github.com/gin-gonic/gin"
)

// SetupRoutes 设置路由
func SetupRoutes(router *gin.Engine) {
	// 获取数据库实例
	db := database.GetDB()
	
	// 初始化模块服务和处理器
	productService := services.NewProductService(db)
	productHandler := handlers.NewProductHandler(productService)
	
	// 基本测试路由
	router.GET("/ping", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
	})

	// 数据库连接测试路由
	router.GET("/db-check", func(c *gin.Context) {
		if db == nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Database connection not initialized"})
			return
		}

		// 测试数据库连接
		var count int64
		if err := db.Raw("SELECT 1").Count(&count).Error; err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "Database query failed: " + err.Error()})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"status":  "success",
			"message": "Database connection is working",
		})
	})
	
	// API版本组
	v1 := router.Group("/v1")
	{
		// 注册产品模块路由
		productHandler.RegisterRoutes(v1)
		
		// 未来可以在这里注册其他模块路由
		// categoryHandler.RegisterRoutes(v1)
		// userHandler.RegisterRoutes(v1)
	}
}